#coding:utf-8
import re,json
def Re(res,total,id = "1"):
    if id == "1":
        data = re.findall(str(res),total)
    if id == "2":
        data = re.findall(str(res),total,re.S)
    return data
class Hitachi():
    def __init__(self,data):
        self.data = data

    def portdata(self):
        data = Re(r"(\d\w),\w+,\w+,\d+,\w+,Point to Point,\w+,(\S{16}),(\S+),",self.data,"2")
        return data
    def host(self):
        data = Re(r"(\d\w),(\S+),\d+,,(\w{16}),,\d+,(\w+-\w+)",self.data,"2")
        return data
    def lundata(self):
        data = Re("\d\w,(\S+),\d+,,\w+,(..:..:..)",self.data,"2")
        return data
from scriptd.towwn import WWn
from san import models
#传送存储ID号码及文本信息
def hitachi_to_data(id,text):
    hitachiscipit = Hitachi(text)
    #端口信息的收录
    portdata = hitachiscipit.portdata()

    for i in portdata:
        if not models.StoragePort.objects.filter(storage_id = id,name = i[2] + "-" +i[0]):
            pdata = {
                "name": i[2] + "-" +i[0],
                "storage_id":id,
            }
            objport = models.StoragePort.objects.create(**pdata)
            wwn = WWn(i[1])
            objwwn = models.Wwn.objects.update_or_create(wwn = wwn)
            objwwn[0].storageport_wwn_id = objport.id
            objwwn[0].storage_wwn_id = id
            objwwn[0].name = pdata["name"]
            objwwn[0].save()
    #存储主机信息表
    hostdata = hitachiscipit.host()
    print(hostdata)
    models.Storagehost.objects.filter(storage_id=id).delete()
    for i in hostdata:
        hdata = {
            "hostname": i[1],
            "hosttype": "",
            "storage_id": id,
        }
        a = models.Storagehost.objects.create(**hdata)
        wwn = WWn(i[2])
        objhostwwn = models.Wwn.objects.update_or_create(wwn=wwn)
        objhostwwn[0].storage_wwn_id = id
        objhostwwn[0].save()
        objhostwwn[0].hostgroup_wwn.add(a)
    # 聚合组
    lundata = hitachiscipit.lundata()
    print(lundata)
    host = []
    for i in lundata:
        host.append(i[0])
    host = list(set(host))
    for i in host:
        lunmess = []
        for k in lundata:
            if i == k[0]:
                lunmess.append(k[1])
        lunmess = list(set(lunmess))
        portmess = []
        for p in hostdata:
            if i == p[1]:
                portmess.append(p[3] + "-" +p[0])
        portmess = list(set(portmess))
        if not models.Hostgroup.objects.filter(storage_id=id,hostgroupname=i,portgroupname=portmess,lungroupname=lunmess):
            data = {
                "storage_id": id,
                "hostgroupname": i,
                "portgroupname":portmess,
                "lungroupname": lunmess,
            }
            models.Hostgroup.objects.create(**data)